<template>
    <headerVue title="登录" backText="" />
    <div class="auth">
        <img class="logo"
            src="https://ts1.cn.mm.bing.net/th/id/R-C.35c06685983af8f052adb6e8d9256cb2?rik=ugOskpEN%2b8uwOA&riu=http%3a%2f%2fimg.jj20.com%2fup%2fallimg%2ftx29%2f05161035027501488.jpg&ehk=nv4HBmtm4063065nTbhDs%2f8QpzCVGzUKDHtxGrCHjNw%3d&risl=&pid=ImgRaw&r=0"
            alt="">
            <div class="tips">用户名及密码应当由字母、数字、下划线组成，且长度在6-20位之间</div>
        <!-- 注册 -->
        <van-form @submit="onSubmit" v-if="type==='register'">
            <van-cell-group inset>
                <van-field v-model="username" name="username" label="用户名" label-width="1.5rem" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model="password" type="password" name="password" label="密码" label-width="1.5rem"  placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
                <van-field v-model="verify"  name="verify" label="验证码" label-width="1.5rem"  placeholder="验证码"
                    :rules="[{ required: true, message: '请填写验证码' }]">
                <template #button>
                    <imgverifyVue ref="verifyRef" @sendImgCode="getImgCode"/>
                </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    注册
                </van-button>
                <p class="change-btn" @click="changeType('login')">已有账号，前往登录</p>
            </div>
        </van-form>


        <!-- 登录 -->
        <van-form @submit="onSubmit" v-else>
            <van-cell-group inset>
                <van-field v-model="username" name="username" label="用户名" label-width="1.5rem" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model="password" type="password" name="password" label="密码" label-width="1.5rem"  placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    登录
                </van-button>
                <p class="change-btn" @click="changeType('register')">没有账号？去注册</p>
            </div>
        </van-form>


    </div>
</template>

<script>
import headerVue from '@/components/header.vue';
import imgverifyVue from '@/components/vueimageverify.vue'
import { toRefs,reactive,ref } from 'vue';
import axios from '../api/axios';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { Toast } from 'vant';
import 'vant/es/toast/style';

export default {
    components: {
        headerVue,
        imgverifyVue
    },
    setup() {
    const router = useRouter()  //得到vuerouter的实例对象
    const verifyRef = ref(null)
    const state = reactive({ 
        username:'',
        password:'',
        type:'login',
        verify:'',
        imgCode:''
     })

     const store = useStore()

     //提交事件
    const onSubmit = async(values) => {
      if(state.type==='login'){ //登录
        //发登录接口请求

        const res = await axios.post('admin/login',{
            username:state.username,
            password:state.password
        })
        Toast.success(res.msg)
        sessionStorage.setItem('token',res.data.token)
        store.commit('setUserInfo',res.data)
        setTimeout(()=>{
            router.push('/home')
        },700)


      }else{        //注册
        if(state.verify.toLocaleLowerCase() !== state.imgCode.toLocaleLowerCase()){
            Toast.fail('验证码不对哦')
            return
            
        }else if(!(/^[A-Za-z0-9_]{6,20}$/.test(state.password)) || !(/^[A-Za-z0-9_]{6,20}$/.test(state.username))){
            Toast.fail('用户名或密码不符合规范')
            return
        }
        else{
            //发注册接口请求
            axios.post('admin/signup',{
                username:state.username,
                password:state.password
            }).then(res=>{
                Toast.success(res.msg) 
                setTimeout(()=>{
                    state.type = 'login'
                },1000)
            })
        }
      }

      
    };

    //切换登录注册函数
    const changeType=(type)=>{
            state.type = type
    }

    //拿到子组件传来的验证码
    const getImgCode = (val)=>{
        state.imgCode = val
    }


    return {
     ...toRefs(state),
      verifyRef,
      onSubmit,
      changeType,
      getImgCode
    };
  },

}
</script>

<style lang="less" scoped>
@import '@/assets/style/custom.less';

.auth {
    height: calc(100vh - 76px);
    padding: 30px 20px 0 20px;
    background: @primary-bg;
    .tips{
        width:99vw;
        margin-bottom: 10px;
        transform:scale(0.8,1)
    }

    .logo {
        width: 150px;
        margin: 0 auto;
        display: block;
        margin-bottom: 30px;
    }
    .change-btn{
        color: @link-color;
        text-align: center;
        margin: 10px auto;
        font-size: 14px;
    }
}
</style>